package cn.s1995.sloth.common.core.convert;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.s1995.sloth.common.core.constant.SecurityConstants;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JoinPrefixUrl
 *
 * @author Lex
 * @description 转换器：拼接url前缀
 * @date 2023/12/28 17:10
 */
@Slf4j
@Component
public class JoinUrlPrefixConvert extends JsonSerializer<Object> {

    @Value("${global.oss-file-url}")
    private String ossFileUrl;

    @Resource
    private HttpServletRequest request;

    @Override
    public void serialize(Object obj, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        try {
            // 字符串||字符串json数组
            if (obj != null && obj instanceof String val) {
                if (StrUtil.isBlank(val)) {
                    gen.writeString(StrUtil.EMPTY);
                    return;
                }

                // 判断是否是json字符串数组
                if (JSONUtil.isTypeJSONArray(val)) {
                    String[] list = JSONUtil.parseArray(obj).toArray(String[]::new);
                    for (int i = 0; i < list.length; i++) {
                        list[i] = buildUrl(list[i]);
                    }
                    gen.writeArray(list, 0, list.length);
                    return;
                }

                // 拼接url前缀
                gen.writeString(buildUrl(val));
                return;
            }

            // 集合
            if (obj != null && obj instanceof ArrayList<?> collection && collection.size() > 0) {
                try {
                    String[] array = collection.stream().map(o -> buildUrl((String) o)).toList().toArray(String[]::new);
                    gen.writeArray(array, 0, array.length);
                } catch (Exception e) {
                    log.error("JoinUrlPrefixConvert ArrayList转换异常 -\nvalue: {}\ntype: {}\n{}", obj, obj.getClass().getTypeName(), e);
                    gen.writeObject(collection);
                }
                return;
            }

            // 字符串数组
            if (obj != null && obj instanceof String[] array && array.length > 0) {
                for (int i = 0; i < array.length; i++) {
                    array[i] = buildUrl(array[i]);
                }

                gen.writeArray(array, 0, array.length);
                return;
            }

        } catch (Exception e) {
            log.error("JoinUrlPrefixConvert 转换异常 -\nvalue: {}\ntype: {}\n{}", obj, obj.getClass().getTypeName(), e);
        }

        gen.writeObject(obj);
    }


    /**
     * 拼接url前缀
     *
     * @param fileName
     * @return
     */
    private String buildUrl(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return StrUtil.EMPTY;
        }
        // http开头的url则不拼接前缀
        if (fileName.startsWith("http")) {
            return fileName;
        }
        //后台访问不拼接
        String header_toc = request.getHeader(SecurityConstants.HEADER_TOC);
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(StrUtil.isNotBlank(authorization) && !SecurityConstants.HEADER_TOC_YES.equals(header_toc)) {
            return fileName;
        }
        return StrUtil.isNotEmpty(ossFileUrl) ? (ossFileUrl + fileName) : fileName;
    }
}
